package com.xm9m.ibczy.dsp.http.bhttp.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by baichuan on 2016/11/22.
 * <P>IOUtils is a utils to read file inputstrean and path to byte[] or byte[] to file outputstram </P>
 * {@link File}
 * {@link FileInputStream}
 * {@link ByteArrayOutputStream}
 */

public class IOUtils {
    public static ByteArrayOutputStream bout;
    private static byte[]  byt = new byte[1024];
    private static byte[] data;
    private static int count = 0;

    /**
     * name:getFromInput
     *
     * @param input inputStream
     * @return byte[] is file data
     * {@code path}
     */
    public static byte[] getFromInput(InputStream input) {
        if (input == null)
            return null;
        try {
            bout = new ByteArrayOutputStream();
            while ((count = input.read(byt)) > 0) {
                bout.write(byt, 0, count);
            }
            data = bout.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bout != null)
                    bout.close();
                if (input != null)
                    input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return data;
    }

    /**
     * name:getDataFromFil
     * function:get data from file
     * {@link File}
     * {@link FileInputStream}
     *
     * @param file file is dataSourse
     * @return byte[] of @param file
     */
    public static byte[] getDataFromFile(File file) {
        if (file == null || !file.exists())
            return null;
        FileInputStream fin = null;

        try {
            fin = new FileInputStream(file);
            data = getFromInput(fin);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fin != null) {
                    fin.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return data;
    }


    /**
     * name:getDataFromPath
     *{@link String}
     * {@link FileInputStream}
     * @param filePath
     * @return
     */
    public static byte[] getDataFromPath(String filePath) {
        if (filePath == null || filePath.length() < 1)
            return null;
        File file = new File(filePath);
        if (!file.exists())
            return null;
        try {
            data = getDataFromFile(new File(filePath));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }
}
